//
//  RaeRequestApiExtension.swift
//  77Club
//
//  Created by Apple on 2024/8/26.
//

import Foundation
import Alamofire
import AdSupport

extension RaeRequestApi {
    
    /// 请求全路径
    /// Request Full Path
    private var urlPath: String {
        let BaseUrl = RaeRequestParameterConfig.shared.baseUrlStr
        let urlString = BaseUrl + path
        return urlString
    }
    
    var userType: String {
        let userT = RaeRequestParameterConfig.shared.userType
        return userT
    }
    
    /// 是否是POST请求
    /// is POST Request
    var isPostRequest: Bool {
        switch self {
        case .logout: return false
        case .delete: return false
        case .loginLog: return false
            
        default:
            return true
        }
    }
    /// GET请求地址
    /// Get Request URL
    private var getRequestUrl: String {
        switch self {
        case .delete:
            return urlPath
        case .loginLog:
            return urlPath + "?userType=\(userType)"
            
        default:
            return ""
        }
    }
    
    /// 请求
    var request: URLRequest {
        if isPostRequest {
            return postRequest
        }else {
            return getRequest
        }
    }
    
    /// Get请求
    /// Get Request
    private var getRequest: URLRequest {
        var request = URLRequest.init(url: URL.init(string: getRequestUrl) ?? URL.init(string: urlPath)!, timeoutInterval: 30)
        request.httpMethod = HTTPMethod.get.rawValue
        if let token = UserDefaultsManager.getString(forKey: .token) {
            request.setValue(token, forHTTPHeaderField: "token")
        }
        return request
    }
    
    /// Post请求
    /// Post Request
    private var postRequest: URLRequest {

        var request = URLRequest.init(url: URL.init(string: urlPath)!, timeoutInterval: 30)
        request.httpMethod = HTTPMethod.post.rawValue
        request.setValue("application/json", forHTTPHeaderField: "Content-Type")
        if let token = UserDefaultsManager.getString(forKey: .token) {
            request.setValue(token, forHTTPHeaderField: "token")
        }
        let data = try? JSONSerialization.data(withJSONObject: parameters, options: JSONSerialization.WritingOptions.prettyPrinted)
        request.httpBody = data
        return request
    }
    
}
